import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import { getAuthShop, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      tData: [{}],
      shopsForAdm: [],
      areaArray: [],
      shopNameArray: [],
      processData: [{}],
      areaSelect: '请选择地区',
      shopSelect: '请选择门店',
    };
  },
  componentWillMount: function() {
    let _this = this;
  },
  componentDidMount: function() {
    let _this = this;
    this.getData();
  },
  getData: function() {
    let _this = this;
    console.log('执行getData');
    fetch(ROOTURL_TABLE + 'cafune/servant/serdaydata.api', { 
	  method: 'GET',
	  headers: { 
	    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
	  },  
	})
	.then((response) => {
 	  if(response.ok) {
		response.json().then(function(data) {
		  this.setState({
			processData: data,
		  }, () => {
	        getAuthShop(null, function(data) {
	          _this.setState({
	            shopsForAdm: data,
	          }, () => {
	            // 处理数据格式为[{}]
	            let processData = [];
	            let ids = _this.state.processData.servantIds;

	            for(var i in ids) {
	              let id = ids[i];
	              processData.push(_this.state.processData[id]);
	            }
	            // 获取权限列表数组(有重复数据)
	            let shopsForAdm = [];
	            _this.state.shopsForAdm.forEach((shopMes) => {
	              shopsForAdm.push(shopMes.dname);
	            }); 
	            // 过滤获取有权限数据与权限列表去重
	            let areaArray = new Set();
	            let shopNameArray = new Set();
	            let permissionData = processData.filter((data) => {
	              if(shopsForAdm.indexOf(data.servantShop) === -1) {
	                return false
	              } else {
	                areaArray.add(data.servantShopLoc);
	                shopNameArray.add(data.servantShop)
	                return true 
	              }
	            });
	            // 设置相应state，并回调执行地区筛选
	            _this.setState({
	              processData: permissionData,
	              areaArray: Array.from(areaArray),
	              shopNameArray: Array.from(shopNameArray),
	            }, () => {
	              _this.filterData();
	            });
	          });
	        }.bind(_this));
	      });
		}.bind(_this));
	  } else {
	  	console.log("Looks like the response wasn't perfect, got status", response.status);
	  }
	})
	.catch((error) => {
	  alert("获取服务器内容失败");
	  console.log('Request failed', error);
	})
  },
  changeArea: function(e) {
    let _this = this;
    let areaSelect = e.target.value;
    this.setState({
      areaSelect: areaSelect,
      shopSelect: '请选择门店',
    }, () => {
      _this.filterData();
    });
  },
  changeShop: function(e) {
  	let _this = this;
    let shopSelect = e.target.value;
    this.setState({
      shopSelect: shopSelect,
    }, () => {
      _this.filterData();
    });
  },
  filterData: function() {// 按地区筛选数据
  	console.log('执行filterData');
    let _this = this;
    let areaSelect = this.state.areaSelect;
    let shopSelect = this.state.shopSelect;
    let selectData = this.state.processData.filter((data) => {
    	if(shopSelect == '请选择门店') {
    		return areaSelect == '请选择地区'||data.servantShopLoc == areaSelect
    	} else {
    		return data.servantShop == shopSelect
    	}
    });
    this.setState({
      tData: selectData,
    });
  },
  render: function() {
    return (
      <div>
        <div>
          <select value={this.state.areaSelect} onChange={this.changeArea}>
            <option value="请选择地区">请选择地区</option>
            {
              !this.state.areaArray[0]||this.state.areaArray.map((area) => {
                return (
                  <option value={area} key={area}>{area}</option>
                );
              })
            }
          </select>
          <select value={this.state.shopSelect} onChange={this.changeShop} className={styles['select']}>
		    <option value="请选择门店">请选择门店</option>
		      {
		        !this.state.shopNameArray[0]||this.state.shopNameArray.map((name, index) => {
		          return (
		            <option key={name} value={name}>{name}</option>
		          );
		        })
		      }
	      </select>
        </div>
        <div>
        <Table data={this.state.tData} className={styles.container}>
	      <Column dataKey='servantName' name='理发师' width="400px" order="false" key={`col-servantName`}/>
	      <Column dataKey='servantShop' name='所属门店' width="400px" order="false" key={`col-servantShop`}/>
	      <Column dataKey='servantShopLoc' name='所属地区' width="400px" order="false" key={`col-servantShopLoc`}/>
	      <Column dataKey='dayServeCount' name='当日服务数' width="400px" order="true" key={`col-dayServeCount`}/>         
	    </Table>
        </div>
      </div>
    );
  }
});